using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Core;
using Admin.NET.Core.Service;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Mapster;
using Microsoft.AspNetCore.Mvc;

namespace Admin.NET.Application.Service.Home;

/// <summary>
/// 常用菜单
/// </summary>
[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class CommonMenuService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<CommonMenu> _rep;

	private readonly SysMenuService _sysMenuService;

	private readonly UserManager _userManager;

	public CommonMenuService(SqlSugarRepository<CommonMenu> rep, SysMenuService sysMenuService, UserManager userManager)
	{
		_rep = rep;
		_sysMenuService = sysMenuService;
		_userManager = userManager;
	}

	[HttpGet("/commonmenu/all")]
	public async Task<dynamic> GetAllCommonMenu()
	{
		return await (from u in _rep.AsQueryable()
			where u.CreateUserId == (long?)_userManager.UserId
			select u).ToListAsync();
	}

	[HttpGet("/commonmenu/allmenuleafs")]
	public async Task<dynamic> GetAllMenuLeafs()
	{
		List<MenuOutput> menus = await _sysMenuService.GetLoginMenuTree();
		List<MenuOutput> leafNodes = new List<MenuOutput>();
		foreach (MenuOutput menu in menus)
		{
			List<MenuOutput> leafs = GetMenuLeafs(menu);
			leafNodes.AddRange(leafs);
		}
		return leafNodes;
	}

	private List<MenuOutput> GetMenuLeafs(MenuOutput menu)
	{
		List<MenuOutput> leafNodes = new List<MenuOutput>();
		if (menu.Children != null)
		{
			foreach (MenuOutput child in menu.Children)
			{
				if (child.Children == null || child.Children.Count == 0)
				{
					leafNodes.Add(child);
				}
				else
				{
					leafNodes.AddRange(GetMenuLeafs(child));
				}
			}
		}
		return leafNodes;
	}

	/// <summary>
	/// 设置常用菜单
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/commonmenu/set")]
	public async Task SetCommonMenu([FromBody] List<SetCommonMenuInput> input)
	{
		try
		{
			await _rep.Context.Ado.BeginTranAsync();
			await (from w in _rep.Context.Deleteable<CommonMenu>()
				where w.CreateUserId == (long?)_userManager.UserId
				select w).ExecuteCommandAsync();
			List<CommonMenu> data = input.Adapt<List<CommonMenu>>();
			await _rep.InsertRangeAsync(data);
			await _rep.Context.Ado.CommitTranAsync();
		}
		catch (Exception ex)
		{
			await _rep.Context.Ado.RollbackTranAsync();
			throw ex;
		}
	}
}
